'use strict';

const moment = require('moment');

const Controller = require('egg').Controller;

class BillController extends Controller {
  async add() {
    const { ctx, app } = this;
    const { amount, type_id, type_name, pay_type, remark = '' } = ctx.request.body;
    if (!amount || !type_id || !type_name || !pay_type) {
      ctx.body = {
        code: 400,
        msg: '参数错误',
        data: null,
      };
    }

    try {
      const token = ctx.request.header.authorization;
      const decode = await app.jwt.verify(token, app.config.jwt.secret);
      if (!decode || !decode.id) {
        return;
      }
      const user_id = decode.id;
      await ctx.service.bill.add({
        amount,
        type_name,
        type_id,
        // date: new Date(),
        pay_type,
        user_id,
        remark,
      });
      ctx.body = {
        code: 200,
        msg: '添加成功',
        data: null,
      };
    } catch (e) {
      console.log(e);
      ctx.body = {
        code: 500,
        msg: '系统错误',
        data: null,
      };
    }
  }

  async list() {
    const { ctx, app } = this;
    const { date, page_num = 1, page_size = 10, type_id = 'all' } = ctx.query;

    try {
      const token = ctx.request.header.authorization;
      const decode = await app.jwt.verify(token, app.config.jwt.secret);
      if (!decode || !decode.id) {
        return;
      }
      const user_id = decode.id;
      const list = await ctx.service.bill.list(user_id);
      const _list = list.filter(item => {
        if (type_id !== 'all') {
          return moment(item.date).format('YYYY-MM') === date && type_id === item.type_id;
        }
        return moment(item.date).format('YYYY-MM') === date;
      });

      const listMap = _list.reduce((acc, cur) => {
        const date = moment(cur.date).format('YYYY-MM-DD');
        const index = acc.findIndex(item => item.date === date);
        if (acc && index > -1) {
          acc[index].bills.push(cur);
        }

        if (acc && acc.length && index === -1) {
          acc.push({
            date, bills: [ cur ],
          });
        }

        if (!acc.length) {
          acc.push({
            date, bills: [ cur ],
          });
        }
        return acc;
        // 时间顺序为倒叙
      }, []).sort((a, b) => moment(b.date) - moment(a.date));

      // 分页处理
      const filterListMap = listMap.slice((page_num - 1) * page_size, page_num * page_size);

      // 计算当月总收入和总支出
      const _tlist = list.filter(d => moment(d.date).format('YYYY-MM') === date);
      const totalExpense = _tlist.reduce((acc, cur) => {
        if (cur.pay_type === 1) {
          acc += (+cur.amount || 0);
        }
        return acc;
      }, 0);
      const totalIncome = _tlist.reduce((acc, cur) => {
        if (cur.pay_type === 2) {
          acc += (+cur.amount || 0);
        }
        return acc;
      }, 0);
      ctx.body = {
        code: 200,
        msg: '请求成功',
        data: {
          totalExpense,
          totalIncome,
          totalPage: Math.ceil(listMap.length / page_size),
          pageSize: +page_size,
          pageNum: +page_num,
          list: filterListMap || [],
        },
      };
    } catch (e) {
      console.log(e);
      ctx.body = {
        code: 500,
        msg: '系统错误',
        data: null,
      };
    }
  }

  async detail() {
    const { ctx, app } = this;
    const { id = '' } = ctx.query;
    const token = ctx.request.header.authorization;
    const decode = await app.jwt.verify(token, app.config.jwt.secret);
    if (!decode || !decode.id) return;
    const user_id = decode.id;
    if (!id) {
      ctx.body = {
        code: 500,
        msg: '订单id不能为空',
        data: null,
      };
      return;
    }

    try {
      const result = await ctx.service.bill.detail(id, user_id);
      ctx.body = {
        code: 200,
        msg: '请求成功',
        data: result,
      };
    } catch (e) {
      console.log(e);
      ctx.body = {
        code: 500,
        msg: '系统错误',
        data: null,
      };
    }
  }

  async update() {
    const { ctx, app } = this;
    const { id, amount, type_id, type_name, pay_type, remark = '' } = ctx.request.body;
    if (!id || !amount || !type_id || !type_name || !pay_type) {
      ctx.body = {
        code: 400,
        msg: '参数错误',
        data: null,
      };
      return;
    }

    try {
      const token = ctx.request.header.authorization;
      const decode = await app.jwt.verify(token, app.config.jwt.secret);
      if (!decode || !decode.id) return;
      const user_id = decode.id;
      await ctx.service.bill.update({
        id,
        amount,
        type_id,
        type_name,
        date: new Date(),
        pay_type,
        remark,
        user_id,
      });
      ctx.body = {
        code: 200,
        msg: '更新成功',
        data: null,
      };
    } catch (e) {
      console.log(e);
      ctx.body = {
        code: 500,
        msg: '系统错误',
        data: null,
      };
    }
  }

  async delete() {
    const { ctx, app } = this;
    const { id } = ctx.request.body;
    if (!id) {
      ctx.body = {
        code: 400,
        msg: '参数错误',
        data: null,
      };
      return;
    }

    try {
      const token = ctx.request.header.authorization;
      const decode = await app.jwt.verify(token, app.config.jwt.secret);
      if (!decode || !decode.id) return;
      const user_id = decode.id;
      await ctx.service.bill.delete(id, user_id);
      ctx.body = {
        code: 200,
        msg: '删除成功',
        data: null,
      };
    } catch (e) {
      console.log(e);
      ctx.body = {
        code: 500,
        msg: '系统错误',
        data: null,
      };
    }
  }

  async data() {
    const { ctx, app } = this;
    const { date = '' } = ctx.query;
    if (!date) {
      ctx.body = {
        code: 400,
        msg: '参数错误',
        data: null,
      };
      return;
    }

    try {
      const token = ctx.request.header.authorization;
      const decode = await app.jwt.verify(token, app.config.jwt.secret);
      if (!decode || !decode.id) return;
      const user_id = decode.id;
      const result = await ctx.service.bill.list(user_id);
      // 选择月份，月初时间
      const start = moment(date).startOf('month').unix() * 1000;
      // 选择月份，月末时间
      const end = moment(date).endOf('month').unix() * 1000;
      const _data = result.filter(d => +d.date > start && +d.date < end);
      // 总支出
      const total_expense = _data.reduce((arr, cur) => {
        if (cur.pay_type === 1) {
          arr += +cur.amount;
        }
        return arr;
      }, 0);
      // 总收入
      const total_income = _data.reduce((arr, cur) => {
        if (cur.pay_type === 2) {
          arr += +cur.amount;
        }
        return arr;
      }, 0);

      // 获取收支构成
      let total_data = _data.reduce((acc, cur) => {
        const index = acc.findIndex(item => item.type_id === cur.type_id);
        if (index === -1) {
          acc.push({
            type_id: cur.type_id,
            type_name: cur.type_name,
            pay_type: cur.pay_type,
            number: +cur.amount,
          });
        }
        if (index > -1) {
          acc[index].number += +cur.amount;
        }
        return acc;
      }, []);

      total_data = total_data.map(item => {
        item.number = Number(Number(item.number).toFixed(2));
        return item;
      });

      ctx.body = {
        code: 200,
        msg: '请求成功',
        data: {
          total_expense: Number(total_expense).toFixed(2),
          total_income: Number(total_income).toFixed(2),
          total_data: total_data || [],
        },
      };
    } catch (e) {
      console.log(e);
      ctx.body = {
        code: 500,
        msg: '系统错误',
        data: null,
      };
    }
  }
}

module.exports = BillController;
